package cn.iune.erp.invoice;

import java.math.BigDecimal;
import java.sql.Date;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.justep.baas.Utils;
import com.justep.baas.data.Row;
import com.justep.baas.data.RowState;
import com.justep.baas.data.Table;
import com.justep.baas.data.Transform;

import cn.iune.erp.setting.ISettingService;

@Transactional
@Service
public class AccountInvoiceServiceImpl implements IAccountInvoiceService {
	
	final static String INVOICE_CLEARED = "cleared"; //已核销
	final static String INVOICE_CLEARING = "clearing"; //部分核销
	final static String INVOICE_UNCLEAR = "unclear"; //未核销
	final static String INVOICE_CLEARED_LABEL = "已核销"; //已核销
	final static String INVOICE_CLEARING_LABEL = "部分核销"; //部分核销
	final static String INVOICE_UNCLEAR_LABEL = "未核销"; //未核销
	
	@Autowired
	private IAccountInvoiceDao dao;
	@Autowired
	private IAccountInvoiceDetailDao detailDao;
	
	@Autowired
	private ISettingService systemCodeService;
	


	@Transactional
	@Override
	public void insert(AccountInvoice a) {
		// TODO Auto-generated method stub
		dao.insert(a);
	}

	@Transactional
	@Override
	public void update(AccountInvoice a) {
		// TODO Auto-generated method stub
		dao.update(a);
	}
	
	@Transactional
	@Override
	public void delete(String fID) {
		dao.delete(fID);
	}

	@Override
	public AccountInvoice getByID(String fID) {
		return dao.getByID(fID);
	}

	@Transactional
	@Override
	public JSONObject save(JSONObject object) throws ParseException  {
		// JSON转换Table
		Table table = Transform.jsonToTable(object);
		
		JSONObject data = new JSONObject();
		data.put("concept", table.getTableName());
		JSONArray rows = new JSONArray();
		List<String> idsNew = new ArrayList<String>();
		List<String> idsDel = new ArrayList<String>();
		
		List<Row> list = table.getRows();
		for(Row row : list){
			JSONObject javaObject= Transform.rowToJavaObject(table, row);
			AccountInvoice obj = JSON.toJavaObject(javaObject, AccountInvoice.class);
			if(RowState.NEW.equals(obj.getRowState())){
				dao.insert(obj);
				idsNew.add(obj.getfID());
			}
			if(RowState.DELETE.equals(obj.getRowState())){
				dao.delete(obj.getfID());
				idsDel.add(obj.getfID());
			}
			if(RowState.EDIT.equals(obj.getRowState())){
				AccountInvoice objNew = dao.update(obj);
				//返回+1后的version到前台BizData中进行刷新，使得前台的version与后台的一致。
				///////////////////////////////////////////////////////////////////////
				JSONObject jsonRow = new JSONObject();
				jsonRow.put("id", obj.getfID());
				jsonRow.put("version", objNew.getVersion());
				rows.add(jsonRow);
				//////////////////////////////////////////////////////////////////////
			}
		}
		
		data.put("rows", rows);
		data.put("idsNew", idsNew);
		data.put("idsDel", idsDel);
		
		return data;
	}
	
	
	@Transactional
	@Override
	public JSONObject saveDetail(JSONObject object) throws ParseException {
		// TODO Auto-generated method stub
		// JSON转换Table
		Table table = Transform.jsonToTable(object);
		
		JSONObject json = new JSONObject();
		json.put("concept", table.getTableName());
		JSONArray rows = new JSONArray();
		
		List<Row> list = table.getRows();
		for(Row row : list){
			JSONObject javaObject= Transform.rowToJavaObject(table, row);
			AccountInvoiceDetail obj = JSON.toJavaObject(javaObject, AccountInvoiceDetail.class);
			if(RowState.NEW.equals(obj.getRowState())){
				detailDao.insert(obj);
			}
			if(RowState.DELETE.equals(obj.getRowState())){
				detailDao.delete(obj.getfID());
			}
			if(RowState.EDIT.equals(obj.getRowState())){
				AccountInvoiceDetail objNew = detailDao.update(obj);
				JSONObject jsonRow = new JSONObject();
				jsonRow.put("id", obj.getfID());
				jsonRow.put("version", objNew.getVersion());
				rows.add(jsonRow);
			}
		}
		
		json.put("rows", rows);
		
		return json;
	}

	@Override
	public List<AccountInvoice> getUnclearYSZKList(String guestNumber, String enterpriseNo) {
		return dao.getUnclearYSZKList(guestNumber, enterpriseNo);
	}
	
	//获取应收应付账款，用于登记会计期间数据
	@Override
	public List<AccountInvoice> getAccountList(String revOpay, Date dateStart, Date dateEnd, String enterpriseNo) {
		return dao.getAccountList(revOpay, dateStart, dateEnd, enterpriseNo);
	}
	
	//获取应收应付账款，用于登记会计期间数据
	@Override
	public List<AccountInvoice> getAccountList(String revOpay, String customerID, Date dateStart, Date dateEnd, String enterpriseNo) {
		return dao.getAccountList(revOpay, customerID, dateStart, dateEnd, enterpriseNo);
	}

	@Transactional
	@Override
	public int confirm(String fID) {
		// TODO Auto-generated method stub
		AccountInvoice a = dao.getByID(fID);
		this.confirm(a);
		return 0;
	}
	@Transactional
	@Override
	public int confirm(AccountInvoice a) {
		// TODO Auto-generated method stub
		a.setState("confirm");
		a.setResultStatus("审核中");
		dao.update(a);
		return 0;
	}

	@Transactional
	@Override
	public int active(String fID) {
		// TODO Auto-generated method stub
		AccountInvoice a = dao.getByID(fID);
		this.active(a);
		return 0;
	}
	@Transactional
	@Override
	public int active(AccountInvoice a) {
		// TODO Auto-generated method stub
		a.setState("active");
		a.setResultStatus("待审核");
		dao.update(a);
		return 0;
	}

	@Transactional
	@Override
	public int open(String fID) {
		AccountInvoice a = dao.getByID(fID);
		this.open(a);
		return 0;
	}
	
	@Transactional
	@Override
	public int open(AccountInvoice a) {
		// TODO Auto-generated method stub
		a.setStatus("open");
		dao.update(a);
		return 0;
	}
	
	@Transactional
	@Override
	public int close(String fID) {
		AccountInvoice a = dao.getByID(fID);
		this.close(a);
		return 0;
	}
	
	@Transactional
	@Override
	public int close(AccountInvoice a) {
		// TODO Auto-generated method stub
		a.setStatus("close");
		dao.update(a);
		return 0;
	}
	
	@Transactional
	@Override
	public int agreeIt(AccountInvoice a,String cUsercode,String cUsername, String userId) {
		// TODO Auto-generated method stub

		a.setAudit("confirm");
		a.setConfirmDate(Utils.getCurrentDate());
		
		a.settUsercode(cUsercode);
		a.settUsername(cUsername);
		a.settDatetime(Utils.getCurrentDateTime());
		
		a.setResultStatus("已审核");

		dao.update(a);

		return 0;
	}

	@Transactional
	@Override
	public int agreeIt(String fID,String cUsercode,String cUsername, String userId) {
		
		// TODO Auto-generated method stub
		AccountInvoice a = dao.getByID(fID);
		
		this.agreeIt(a, cUsercode, cUsername,  userId);
		 
		return 0;
	}
	
	@Transactional
	@Override
	public int unAgree(AccountInvoice a) {
		// TODO Auto-generated method stub
		
		a.setAudit("active");
		a.setConfirmDate(null);
		
		a.settUsercode(null);
		a.settUsername(null);
		a.settDatetime(null);
		
		a.setResultStatus("审核中");
		
		dao.update(a);

		return 0;
	}
	
	@Transactional
	@Override
	public int unAgree(String fID) {
		// TODO Auto-generated method stub

		//判断是否可以撤销
		AccountInvoice a = dao.getByID(fID);
		
		this.unAgree(a);
		
		return 0;
	}
	
	
	//增加应收应付核销金额（发票）
	@Transactional
	@Override
	public int orderAmountClearedAdd(
			String accountInvoiceNo
			,String enterpriseNo
			,BigDecimal orderAmountCleared
			,BigDecimal discountCash
			){
		
		AccountInvoice a = null;
		a = dao.getByNo(accountInvoiceNo, enterpriseNo);

		a.setOrderAmountCleared(a.getOrderAmountCleared().add(orderAmountCleared));
		
//		String handling = a.getHandling();
		
//		System.out.println("系统信息-->更新核销金额orderAmountCleared:"+orderAmountCleared);
//		System.out.println("系统信息-->更新账核销金额accountAmountCleared:"+accountAmountCleared);
//		System.out.println("系统信息-->更新账核销金额a.getfID():"+a.getfID());
//		System.out.println("系统信息-->更新账核销金额a.getOrderAmountTotal:"+a.getOrderAmountTotal());
//		System.out.println("系统信息-->更新账核销金额a.getAccountAmountTotal():"+a.getAccountAmountTotal());
		//普通
		a.setDiscountCash(a.getDiscountCash().add(discountCash));//现金折扣与票据余额无关。
		a.setPendingAmount(a.getPendingAmount().subtract(orderAmountCleared));
//		int direction = a.getDirection();
//		BigDecimal bgDirection = new BigDecimal(direction);
//		BigDecimal accountPending = a.getPendingAmount().multiply(bgDirection).setScale(2, BigDecimal.ROUND_HALF_UP);
//		a.setAccountPending(accountPending);
		
		if(a.getOrderAmountTotal().compareTo(a.getPendingAmount())==0) {
			//票据余额=票据总额，未核销
			a.setHandling(INVOICE_UNCLEAR);
			a.setHandlingLabel(INVOICE_UNCLEAR_LABEL);
		}else if(a.getPendingAmount().compareTo(BigDecimal.ZERO)>0 && a.getPendingAmount().compareTo(a.getOrderAmountTotal())<0) {
			//票据余额>0,并且票据余额<单据总额，部分核销
			a.setHandling(INVOICE_CLEARING);
			a.setHandlingLabel(INVOICE_CLEARING_LABEL);
		}else {
			//票据余额=0，已核销
			a.setHandling(INVOICE_CLEARED);
			a.setHandlingLabel(INVOICE_CLEARED_LABEL);
		}
		System.out.println("a.getHandlingLabel()-->>"+a.getHandlingLabel());
		
		a.setClearDatetime(Utils.getCurrentDateTime());
		
		dao.update(a);

		return 0;
	}
	
	//减少应收应付核销金额（发票）
	@Transactional
	@Override
	public int orderAmountClearedSub(
			String accountInvoiceNo
			,String enterpriseNo
			,BigDecimal orderAmountCleared
			,BigDecimal discountCash
			){
		
		AccountInvoice a = null;
		a = dao.getByNo(accountInvoiceNo, enterpriseNo);

		a.setOrderAmountCleared(a.getOrderAmountCleared().subtract(orderAmountCleared));
//		String handling = a.getHandling();
		
//		System.out.println("系统信息-->更新核销金额orderAmountCleared:"+orderAmountCleared);
//		System.out.println("系统信息-->更新账核销金额accountAmountCleared:"+accountAmountCleared);
//		System.out.println("系统信息-->更新账核销金额a.getfID():"+a.getfID());
//		System.out.println("系统信息-->更新账核销金额a.getOrderAmountTotal:"+a.getOrderAmountTotal());
//		System.out.println("系统信息-->更新账核销金额a.getAccountAmountTotal():"+a.getAccountAmountTotal());
		//普通
		a.setDiscountCash(a.getDiscountCash().subtract(discountCash));//现金折扣与票据余额无关。
		a.setPendingAmount(a.getPendingAmount().add(orderAmountCleared));
//		int direction = a.getDirection();
//		BigDecimal bgDirection = new BigDecimal(direction);
//		BigDecimal accountPending = a.getPendingAmount().multiply(bgDirection).setScale(2, BigDecimal.ROUND_HALF_UP);
//		a.setAccountPending(accountPending);
		
		if(a.getOrderAmountTotal().compareTo(a.getPendingAmount())==0) {
			//票据余额=票据总额，未核销
			a.setHandling(INVOICE_UNCLEAR);
			a.setHandlingLabel(INVOICE_UNCLEAR_LABEL);
		}else if(a.getPendingAmount().compareTo(BigDecimal.ZERO)>0 && a.getPendingAmount().compareTo(a.getOrderAmountTotal())<0) {
			//票据余额>0,并且票据余额<单据总额，部分核销
			a.setHandling(INVOICE_CLEARING);
			a.setHandlingLabel(INVOICE_CLEARING_LABEL);
		}else {
			//票据余额=0，已核销
			a.setHandling(INVOICE_CLEARED);
			a.setHandlingLabel(INVOICE_CLEARED_LABEL);
		}
		System.out.println("a.getHandlingLabel()-->>"+a.getHandlingLabel());
		
		a.setClearDatetime(Utils.getCurrentDateTime());
		
		dao.update(a);

		return 0;
	}

	//更新现结收款单号
	/*
	@Transactional
	public int updateNextNo(
			String accountInvoiceNo
			,String enterpriseNo
			,String autoPayment
			,String next
			,String nextName
			,String nextNo
			,String settleCategory
			,String settleCategoryLabel
			){
		
		AccountInvoice a = dao.getXSFPByNo(accountInvoiceNo, enterpriseNo);
		a.setNext(next);
		a.setNextName(nextName);
		a.setNextNo(nextNo);
		
		//结算方式
		a.setSettleCategory(settleCategory);
		a.setSettleCategoryLabel(settleCategoryLabel);
		
		//现结
		a.setAutoPayment(autoPayment);
		
		dao.update(a);
		
		return 0;
	}
	*/

	@Transactional
	@Override
	public int updateMaxDetailNo(
			String fID
			,int maxDetailNo){
		
		AccountInvoice a = dao.getByID(fID);
		a.setMaxDetailNo( maxDetailNo );
		//更新数据库入库数量
		dao.update(a);
		return 0;
	}	
	
	@Transactional
	@Override
	public int updateMaxDetailNo(
			String accountInvoiceNo
			,String billType
			,String enterpriseNo
			,int maxDetailNo){
		
		AccountInvoice a = dao.getByNo(accountInvoiceNo, enterpriseNo);
		a.setMaxDetailNo( maxDetailNo );
		//更新数据库入库数量
		dao.update(a);
		return 0;
	}	
	
	//设置合计金额
	
	@Transactional
	@Override
	public int updateAllAmount(
			String fID
			, BigDecimal itemAmount
			, BigDecimal orderAmount
			, BigDecimal orderAmountOld
			, BigDecimal orderAmountTax
			, BigDecimal orderAmountTotal
			, BigDecimal accountAmountOld
			, BigDecimal accountAmountTax
			, BigDecimal accountAmountTotal

		){
		
		AccountInvoice a = dao.getByID(fID);

		a.setItemAmount(itemAmount);
		a.setOrderAmount(orderAmount);
		a.setOrderAmountOld(orderAmountOld);
		a.setOrderAmountTax(orderAmountTax);
		a.setOrderAmountTotal(orderAmountTotal);
		
		a.setAccountAmountOld(accountAmountOld);
		a.setAccountAmountTax(accountAmountTax);
		a.setAccountAmountTotal(accountAmountTotal);

		dao.update(a);
		
		//更新数据库入库数量

		return 0;
	}
	
	//更新结算方式
	@Transactional
	@Override
	public AccountInvoice updateSettleCategory(String fID, String settleCategory ,String settleCategoryLabel){
		AccountInvoice a = dao.getByID(fID);
		if(a==null) return null;
		a.setSettleCategory(settleCategory);
		a.setSettleCategoryLabel(settleCategoryLabel);

		dao.update(a);
		
		return a;
	}

	
	//作为主表
	@Override
	public AccountInvoice packing(
			String billType
			,String billTypeName 
			,String systemCode 
			,int flowType 
			,String revOpay 
			,int direction 
//			,String costingCode 
			,String autoCode 
			,String origin 
			,String originName 
			,String billNo 

			,String cUsercode//=com.justep.system.context.ContextHelper.getOperator().getCode();
			,String cUsername//=com.justep.system.context.ContextHelper.getOperator().getName();
			,String userId //= com.justep.system.context.ContextHelper.getOperator().getID();
			,String employeeNo 
			,String employeeName 
			,String enterpriseNo //= this.getEnterpriseNo();
			,String enterpriseName //= this.getEnterpriseName();
			){
		
		
		//SysInfo中记录的ID
		String APPID = null;
		if(billType.equals("XSFP")){
			APPID = "ff78c72a3fa08d8194b916b2eda24740";//销售发票ID
		}
		if(billType.equals("CGFP")){
			APPID = "452fefd678f9eefdfabd467fb36000a0";//采购发票ID
		}
		if(billType.equals("QTYS")){
			APPID = "8811a1d3e261a137433b47b82317ce9b";//其他应收单ID
		}
		if(billType.equals("QTYF")){
			APPID = "df549d827115b69a757c9866a5c2964a";//其他应付单ID
		}
		
		
		
		AccountInvoice obj = new AccountInvoice();
		String fID = Utils.getUUID();
		obj.setfID(fID);
		
		//单号
		/*
		Map<String,Object> map = usercenterService.getBillParam(billType, enterpriseNo);
		String billTypeName = (String) map.get("billTypeName");
//		String systemCode = (String) map.get("systemCode");
		int flowType = (int) map.get("flowType");
		String revOpay = (String) map.get("revOpay");
		int direction = (int) map.get("direction");
//		String costingCode = (String) map.get("costingCode");
		String autoCode = (String) map.get("autoCode");
		String origin = (String) map.get("origin");
		String originName = (String) map.get("originName");
		if("Y".equals(autoCode)){
			String billNo = (String) map.get("billNo");
			obj.setAccountInvoiceNo(billNo);
			obj.setWriteOffNo(billNo);
		}
		*/
		if("Y".equals(autoCode)){
			obj.setAccountInvoiceNo(billNo);
		}
		
		obj.setBillType(billType);
		obj.setBillTypeName(billTypeName);
		obj.setSystemCode(APPID);//APPID
		obj.setFlowType(flowType);
		obj.setRevOpay(revOpay);
		obj.setDirection(direction);
		obj.setOrigin(origin);
		obj.setOriginName(originName);
		
//		obj.setState("active");
//		obj.setStatus("open");
//		obj.setAudit("active");
		obj.setOrderDate(Utils.getCurrentDate());
		
		obj.setAccountAmountOld(BigDecimal.ZERO);
		obj.setAccountAmountTax(BigDecimal.ZERO);
		
		obj.setItemAmount(BigDecimal.ZERO);
		obj.setOrderAmount(BigDecimal.ZERO);
		obj.setOrderAmountOld(BigDecimal.ZERO);
		obj.setOrderAmountTax(BigDecimal.ZERO);
		
		obj.setOrderAmountTotal(BigDecimal.ZERO);
		obj.setPendingAmount(BigDecimal.ZERO);
		obj.setDiscountCash(BigDecimal.ZERO);
		obj.setOrderAmountCleared(BigDecimal.ZERO);
		
		obj.setDiscountAmount(BigDecimal.ZERO);
		
		obj.setAccountAmountTotal(BigDecimal.ZERO);
//		obj.setAccountPending(BigDecimal.ZERO);
		
		obj.setDiscountRate(BigDecimal.ONE);

//		obj.setReceiveCashAmount(BigDecimal.ZERO);
//		obj.setGiveChangeAmount(BigDecimal.ZERO);
		obj.setTaxRate(BigDecimal.ZERO);
		
		obj.setEmployeeNo(employeeNo);
		obj.setEmployeeName(employeeName);
		
//		obj.setComments("来自商城");
		
		obj.setcUsercode(cUsercode);
		obj.setcUsername(cUsername);
		obj.setcDatetime(Utils.getCurrentDateTime());
		obj.setUserId(userId);
		obj.setEnterpriseNo(enterpriseNo);
		obj.setEnterpriseName(enterpriseName);
		
		obj.setDetailsCount(0);
		obj.setDetailsCountState(0);
		obj.setMaxDetailNo(0);
//		
		obj.setVersion(0);
		
		
		return obj;
	}
	
	//作为主表
	@Override
	public AccountInvoice packing(
			String cUsercode//=com.justep.system.context.ContextHelper.getOperator().getCode();
			,String cUsername//=com.justep.system.context.ContextHelper.getOperator().getName();
			,String userId //= com.justep.system.context.ContextHelper.getOperator().getID();
			,String enterpriseNo //= this.getEnterpriseNo();
			,String enterpriseName //= this.getEnterpriseName();
			){
		
		
		//SysInfo中记录的ID
		String APPID = null;
		
		AccountInvoice obj = new AccountInvoice();
		String fID = Utils.getUUID();
		obj.setfID(fID);
		
		obj.setSystemCode(APPID);
		//单号
		
		obj.setState("active");
		obj.setStatus("open");
		obj.setAudit("active");
		obj.setOrderDate(Utils.getCurrentDate());
		
		obj.setAccountAmountOld(BigDecimal.ZERO);
		obj.setAccountAmountTax(BigDecimal.ZERO);
		
		obj.setItemAmount(BigDecimal.ZERO);
		obj.setOrderAmount(BigDecimal.ZERO);
		obj.setOrderAmountOld(BigDecimal.ZERO);
		obj.setOrderAmountTax(BigDecimal.ZERO);
		
		obj.setOrderAmountTotal(BigDecimal.ZERO);
		obj.setPendingAmount(BigDecimal.ZERO);
		obj.setDiscountCash(BigDecimal.ZERO);
		obj.setOrderAmountCleared(BigDecimal.ZERO);
		
		obj.setDiscountAmount(BigDecimal.ZERO);
		
		obj.setAccountAmountTotal(BigDecimal.ZERO);
//		obj.setAccountPending(BigDecimal.ZERO);
		
		obj.setDiscountRate(BigDecimal.ONE);

//		obj.setReceiveCashAmount(BigDecimal.ZERO);
//		obj.setGiveChangeAmount(BigDecimal.ZERO);
		obj.setTaxRate(BigDecimal.ZERO);
		
//		obj.setEmployeeNo(null);
//		obj.setEmployeeName(null);
		
//		obj.setComments("来自商城");
		
		obj.setcUsercode(cUsercode);
		obj.setcUsername(cUsername);
		obj.setcDatetime(Utils.getCurrentDateTime());
		obj.setUserId(userId);
		obj.setEnterpriseNo(enterpriseNo);
		obj.setEnterpriseName(enterpriseName);
		
		obj.setDetailsCount(0);
		obj.setDetailsCountState(0);
		obj.setMaxDetailNo(0);
//		
		obj.setVersion(0);
		
		
		return obj;
	}
	
	
	//插入代收运费结算单
	@Transactional
	@Override
	public AccountInvoice accountInvoiceDSYFInsert(
			String serialNumber,
			
			String origin,
			String originName,
			String originNo,
			
			String dealObject,
			String dealObjectLabel,
			String customerID,
			String customerNo,
			String shortName,
			String customerName,
			
			BigDecimal orderAmount,
			String settleCategory,
			String settleCategoryLabel,
			
			String orderNo,
			String projectNo,
			
			String cUsercode,String cUsername,String userId,
			String employeeNo,String employeeName,
			
			String enterpriseNo,
			String enterpriseName

			){

		
		
		//获取会计科目（结算账户）的全路径信息
	//	AccountCaption accountCaption = accountCaptionService.getByID(captionID);
	//	String captionFullNo = null;// accountCaption.getCaptionFullNo();
	//	String captionFullName = null;// accountCaption.getCaptionFullName();
		String billType = "QTYS";
		
		Map<String,Object> map = systemCodeService.getBillParam(billType, enterpriseNo);
		String billTypeName = (String) map.get("billTypeName");
		String systemCode = (String) map.get("systemCode");
		int flowType = (int) map.get("flowType");
		String revOpay = (String) map.get("revOpay");
		int direction = (int) map.get("direction");
//		String costingCode = (String) map.get("costingCode");
		String autoCode = (String) map.get("autoCode");
//		String origin = (String) map.get("origin");
//		String originName = (String) map.get("originName");
		String billNo = (String) map.get("billNo");
		
		//打包主表AccountInvoice
		AccountInvoice accountInvoice = this.packing(billType, billTypeName, systemCode, flowType, revOpay, direction, autoCode, origin, originName, billNo, cUsercode, cUsername, userId, employeeNo, employeeName, enterpriseNo, enterpriseName);
	
		accountInvoice.setGuestNumber(serialNumber);
		
		accountInvoice.setBillType(billType);
		accountInvoice.setBillTypeName(billTypeName);
		
	//	accountInvoice.setDirection(direction);
//		int direction = accountInvoice.getDirection();
		BigDecimal bgDirection = new BigDecimal(direction);
		
//		accountInvoice.setState("confirm");
//		accountInvoice.setAudit("confirm");
//		accountInvoice.setResultStatus("已审核");
		
		accountInvoice.setEmployeeNo(employeeNo);
		accountInvoice.setEmployeeName(employeeName);
		
		accountInvoice.setOrderNo(orderNo);
		
		accountInvoice.setOrigin(origin);
		accountInvoice.setOriginName(originName);
		accountInvoice.setOriginNo(originNo);
		
		accountInvoice.setDealObject(dealObject);
		accountInvoice.setDealObjectLabel(dealObjectLabel);
		accountInvoice.setCustomerID(customerID);
		accountInvoice.setCustomerNo(customerNo);
		accountInvoice.setShortName(shortName);
		accountInvoice.setCustomerName(customerName);
		
		accountInvoice.setSettleCategory(settleCategory);
		accountInvoice.setSettleCategoryLabel(settleCategoryLabel);
		accountInvoice.setInvoiceDate(Utils.getCurrentDate());
		accountInvoice.setInvoiceCode(null);//结算号
		
		accountInvoice.setInvoiceCategory(null);
		accountInvoice.setInvoiceCategoryLabel(null);
		
		////////////////////////////////////////////////////////////////////////////////////////////
		accountInvoice.setItemAmount(BigDecimal.ZERO);
		accountInvoice.setOrderAmount(orderAmount);
		accountInvoice.setOrderAmountOld(accountInvoice.getOrderAmount());
		accountInvoice.setOrderAmountTax(BigDecimal.ZERO);
		accountInvoice.setOrderAmountTotal(accountInvoice.getOrderAmount());
		
		accountInvoice.setDepositRate(BigDecimal.ZERO);
		accountInvoice.setDiscountAmount(BigDecimal.ZERO);
		accountInvoice.setDiscountRate(BigDecimal.ONE);
		accountInvoice.setDiscountCash(BigDecimal.ZERO);
		
		accountInvoice.setPendingAmount(accountInvoice.getOrderAmount());
		
		//账金额，保留两位小数
		BigDecimal accountAmountOld = accountInvoice.getOrderAmountOld().multiply(bgDirection);
		accountAmountOld.divide(BigDecimal.ONE, 2, BigDecimal.ROUND_HALF_UP);
		BigDecimal accountAmountTax = accountInvoice.getOrderAmountTax().multiply(bgDirection);
		accountAmountTax.divide(BigDecimal.ONE, 2, BigDecimal.ROUND_HALF_UP);
		BigDecimal accountAmountTotal = accountInvoice.getOrderAmountTotal().multiply(bgDirection);
		accountAmountTotal.divide(BigDecimal.ONE, 2, BigDecimal.ROUND_HALF_UP);
		accountInvoice.setAccountAmountOld(accountAmountOld);
		accountInvoice.setAccountAmountTax(accountAmountTax);
		accountInvoice.setAccountAmountTotal(accountAmountTotal);

		accountInvoice.setComments("代收运费结算单");
		////////////////////////////////////////////////////////////////////////////////////////////
//		if(flowType!=null) {
//			accountInvoice.setFlowType(Integer.parseInt(flowType));
//		}
		
		//写入数据库主表
		dao.insert(accountInvoice);
		
		return accountInvoice;
	}

	
	//应收账款进
	@Override
	public BigDecimal getReceiveAmountTotay(List<Object> params) {
		return dao.getReceiveAmountTotay(params);
	}

	
	//应付账款金额
	@Override
	public BigDecimal getPayableAmountTotay(List<Object> params) {
		return dao.getPayableAmountTotay(params);
	}

	@Override
	public AccountInvoice getByNo(String accountInvoiceNo, String enterpriseNo) {
		// TODO Auto-generated method stub
		return dao.getByNo(accountInvoiceNo, enterpriseNo);
	}

	@Override
	public AccountInvoice getQTYSByOriginNo(String origin, String originNo, String enterpriseNo) {
		return dao.getQTYSByOriginNo(origin, originNo, enterpriseNo);
	}

	@Override
	public AccountInvoice getByNextNo(String next, String nextNo, String enterpriseNo) {
		// TODO Auto-generated method stub
		return dao.getByNextNo(next, nextNo, enterpriseNo);
	}

	
	@Override
	public JSONObject newData(JSONObject data) {
		return dao.create(data);
	}
	
	@Override
	public JSONObject deleteData(JSONObject param) {
		
		JSONArray ids = param.getJSONArray("ids");
		for(int i=0;i<ids.size();i++){
			String id = ids.getString(i);
			//这里可以增加是否可删除的判断
			
			//首先删除子表
			List<AccountInvoiceDetail> sods = detailDao.getByMasterID(id);
			for(AccountInvoiceDetail sod:sods){
				detailDao.delete(sod.getfID());
			}

			//然后删除主表
			dao.delete(id);
		}

		JSONObject data = new JSONObject();
		data.put("ids", ids);
		
		JSONObject json = new JSONObject();
		json.put("code", 0);
		json.put("msg", "success");
		json.put("data", data);
		
		return json;
	}
	
	@Override
	public JSONObject saveData(JSONObject param) {
		// TODO Auto-generated method stub
		JSONObject data;
		try {
			//保存主表
			data = this.save(param);
			
			//保存从表
			JSONArray slaves = param.getJSONArray("slaves");
			if(slaves.size()>0) {
				JSONObject slaveParam = slaves.getJSONObject(0);
				JSONObject slaveData = this.saveDetail(slaveParam);
				JSONArray slaveDatas = new JSONArray();
				slaveDatas.add(slaveData);
				data.put("slaves", slaveDatas);
			}
					
			JSONObject json = new JSONObject();
			json.put("code", 0);
			json.put("msg", "success");
			json.put("data", data);
			
			return json;
			
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			
			JSONObject json = new JSONObject();
			json.put("code", -1);
			json.put("msg", e.getMessage());
			
			return json;
		} 
	}
	
	@Override
	public JSONObject queryData(JSONObject param) {
		// TODO Auto-generated method stub
		try {
			JSONObject jsonTable = dao.query(param);
			
			JSONObject json = new JSONObject();
			json.put("code", 0);
			json.put("msg", "success");
			json.put("data", jsonTable);
			
			return json;
		} catch (SQLException e) {
			e.printStackTrace();
			
			JSONObject json = new JSONObject();
			json.put("code", -1);
			json.put("msg", e.getMessage());
			return json;
		}
	}
	
	@Override
	public JSONObject jointData(JSONObject param) {
		// TODO Auto-generated method stub
		try {
			JSONObject jsonTable = dao.joint(param);
			
			JSONObject json = new JSONObject();
			json.put("code", 0);
			json.put("msg", "success");
			json.put("data", jsonTable);
			
			return json;
		} catch (SQLException e) {
			e.printStackTrace();
			
			JSONObject json = new JSONObject();
			json.put("code", -1);
			json.put("msg", e.getMessage());
			return json;
		}
	}
	
	@Override
	public JSONObject validData(JSONObject param) {
		// TODO Auto-generated method stub
		return null;
	}

	//新增子表
	@Override
	public JSONObject newDataDetail(JSONObject data) {
		return detailDao.create(data);
	}
	
	//查询子表
	@Override
	public JSONObject queryDataDetail(JSONObject param) {
		// TODO Auto-generated method stub
		try {
			JSONObject jsonTable = detailDao.query(param);
			
			JSONObject json = new JSONObject();
			json.put("code", 0);
			json.put("msg", "success");
			json.put("data", jsonTable);
			
			return json;
		} catch (SQLException e) {
			e.printStackTrace();
			
			JSONObject json = new JSONObject();
			json.put("code", -1);
			json.put("msg", e.getMessage());
			return json;
		}
	}


}
